<?php

namespace App\Http\Controllers;

use App\Models\DossierTemplate;
use App\Services\CommonService;
use App\Services\DossierTemplateService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Storage;

/**
 * 案卷构成模板
 */
class DossierTemplateController extends Controller
{
    public $dossierTemplateService;

    public function __construct(DossierTemplateService $dossierTemplateService)
    {
        parent::__construct();
        $this->dossierTemplateService = $dossierTemplateService;
    }

    /**
     * 列表数据
     */
    public function index(Request $request)
    {
        $perPage = $request->input('per_page') ?: $this->limit;

        $list = $this->dossierTemplateService->getList($request, $perPage);

        return $this->success($list);
    }

    /**
     * 案卷构成模板保存数据
     */
    public function store(Request $request)
    {
        if (!$this->dossierTemplateService->saveData($request->all())) {
            return $this->error('保存失败');
        }

        return $this->success('', '保存成功！');
    }

    /**
     * 文件下载
     */
    public function download(Request $request)
    {
        $fileUrl = $request->input('file_url');
        $originName = $request->input('origin_name');

        $ext = pathinfo($fileUrl, PATHINFO_EXTENSION); //获取文件后缀

        if (empty($fileUrl)) {
            return $this->error('file_url 不能为空');
        }
        return Storage::disk('public')->download($fileUrl, $originName.'.'.$ext);
    }


    /**
     * 回收站列表（进行软删除的数据）
     */
    public function recycle(Request $request)
    {
        $data = $this->dossierTemplateService->getRecycles($request);

        return $this->success($data);
    }

    /**
     * 批量软删除，ids可以是以","逗号分割的字符串，也可以是数组形式
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/2/3 15:32
     */
    public function destroyMore(Request $request) : JsonResponse
    {
        $ids = to_array($request->input('ids'));
        if (!DossierTemplate::destroy($ids)) {
            return $this->error('删除失败！');
        };
        $idsStr = implode(',', $ids);
        CommonService::addActionLog('批量软删除案卷构成模板', "数据ID：{$idsStr}");

        return $this->success('', '删除成功');
    }

    /**
     * 恢复批量数据
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/2/3 15:31
     */
    function retrieveMore(Request $request) : JsonResponse
    {
        $ids = to_array($request->input('ids'));
        if (!DossierTemplate::query()->whereIn('id', $ids)->restore()) {
            return $this->error('恢复失败！');
        }
        $ids = implode(',', $ids);
        CommonService::addActionLog('批量恢复案卷构成模板', "数据ID：{$ids}");

        return $this->success('', '恢复成功');
    }

}
